package com.zhangc.blog.admin.web.security;

import java.util.HashSet;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.zhangc.blog.admin.entity.UserEntity;
import com.zhangc.blog.admin.mapper.UserMapper;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // Let people login with either username or email(没有支持)
        UserEntity user = userMapper.findByUsernameOrEmail(s);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username " + s);
        }
        List<String> authCodes = userMapper.getApisById(user.getId());
        user.setAuthCodeList(new HashSet<>(authCodes));
        return UserPrincipal.create(user);
    }

    public UserDetails loadUserById(Long id) {
        UserEntity user = userMapper.queryUserById(id);
        if (user == null) {
            logger.error("user not found,id={}", id);
            return null;
        }
        List<String> authCodes = userMapper.getApisById(id);
        user.setAuthCodeList(new HashSet<>(authCodes));
        return UserPrincipal.create(user);
    }
}
